package com.qc.qx.services.impl;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.qc.qx.services.ThumbnailAWTService;

@Service
public class ThumbnailAWTServiceImpl implements ThumbnailAWTService {

	public static final int WIDTH = 100;
	public static final int HEIGHT = 100;

	public String thumbnail(CommonsMultipartFile file, String uploadPath, String realUploadPath) {
		OutputStream os = null;

		String desc = realUploadPath + "/thum_" + file.getOriginalFilename();
		try {
			os = new FileOutputStream(desc);

			Image image = ImageIO.read(file.getInputStream());
			int width = image.getWidth(null);// 获得原图的宽度
			int height = image.getHeight(null);// 获得原图的高度

			int rete1 = width / WIDTH;// 宽度缩略比例
			int rete2 = height / HEIGHT;// 高度缩略比例

			int rete = 0;
			if (rete1 > rete2) {
				rete = rete1;
			} else {
				rete = rete2;
			}
			// 计算缩略图最总的宽度和高度
			int newWidth = width / rete;
			int newHeight = height / rete;

			BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
			bufferedImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, image.SCALE_SMOOTH), 0, 0, null);

			String imageType = file.getContentType().substring(file.getContentType().indexOf("/") + 1);
			ImageIO.write(bufferedImage, imageType, os);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return uploadPath + "/thum_" + file.getOriginalFilename();
	}
}
